1 using System;
2 using UnityEngine;
3 using UnityStandardAssets.CrossPlatformInput;
4
5 namespace UnityStandardAssets.Characters.ThirdPerson
6 {
7 [RequireComponent(typeof (ThirdPersonCharacter))]
8 public class ThirdPersonUserControl : MonoBehaviour
9 {
10 private ThirdPersonCharacter m_Character; // A reference to the ThirdPersonCharacter on the object
11 private Transform m_Cam; // A reference to the main camera in the scenes transform
12 private Vector3 m_CamForward; // The current forward direction of the camera
13 private Vector3 m_Move;
14 private bool m_Jump; // the world-relative desired move direction, calculated from the camForward and user input.
15
16
17 private void Start()
18 {
19 // get the transform of the main camera
20 if (Camera.main != null)
21 {
22 m_Cam = Camera.main.transform;
23 }
24 else
25 {
26 Debug.LogWarning(
27 "Warning: no main camera found. Third person character needs a Camera tagged \"MainCamera\", for camera-relative controls.", gameObject);
28 // we use self-relative controls in this case, which probably isn't what the user wants, but hey, we warned them!
29 }
30
31 // get the third person character ( this should never be null due to require component )
32 m_Character = GetComponent<ThirdPersonCharacter>();
33 }
34
35
36 private void Update()
37 {
38 if (!m_Jump)
39 {
40 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
41 }
42 }
43
44
45 // Fixed update is called in sync with physics
46 private void FixedUpdate()
47 {
48 // read inputs
49 float h = CrossPlatformInputManager.GetAxis("Horizontal");
50 float v = CrossPlatformInputManager.GetAxis("Vertical");
51 bool crouch = Input.GetKey(KeyCode.C);
52
53 // calculate move direction to pass to character
54 if (m_Cam != null)
55 {
56 // calculate camera relative direction to move:
57 m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
58 m_Move = v*m_CamForward + h*m_Cam.right;
59 }
60 else
61 {
62 // we use world-relative directions in the case of no main camera
63 m_Move = v*Vector3.forward + h*Vector3.right;
64 }
65 #if !MOBILE_INPUT
66 // walk speed multiplier
67 if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
68 #endif
69
70 // pass all parameters to the character control script
71 m_Character.Move(m_Move, crouch, m_Jump);
72 m_Jump = false;
73 }
74 }
75 }